// import TIM from 'tim-js-sdk';
import TencentCloudChat, { ChatSDK } from '@tencentcloud/chat';
import TIMUploadPlugin from 'tim-upload-plugin';
import { getUserSig } from '@/business/services/im';
// import TIMProfanityFilterPlugin from 'tim-profanity-filter-plugin';
import Taro from '@tarojs/taro';
// // App SDKAppID (在腾讯云控制台获取)

// declare the global wx object provided by the WeChat mini-program environment
declare const wx: any;

export const sdkConfig : {
  SDKAppID: number;
  isReady: boolean;
} = {
  SDKAppID: 1600109515,
  isReady: false,
}

// export default tim;
export const initSdk = async () => {
  const userId =  Taro.getStorageSync('imUserSig');
  if (!userId) {
    console.log('No userId found in storage, cannot initialize SDK');
    return;
  }
  if (wx.$TUIKit && sdkConfig.isReady) {
    return;
  }
  Taro.setStorageSync('sdkLoading', true)
  // if (sdkConfig.chat) return;
  const res = await getUserSig()
  wx.$TUIKit = TencentCloudChat.create({
      SDKAppID: 1600109515
  });
  wx.$chat_SDKAppID = 1600109515;
  wx.TencentCloudChat = TencentCloudChat;
  wx.$chat_userID = userId;
    wx.$chat_userSig = res.data;
  wx.$TUIKit.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
  wx.$TUIKit.registerPlugin({'tim-upload-plugin': TIMUploadPlugin});
  // wx.$TUIKit.registerPlugin({ 'tim-profanity-filter-plugin': TIMProfanityFilterPlugin });
        // 登录 Chat
        // 监听 SDK_READY 事件
  wx.$TUIKit.on(TencentCloudChat.EVENT.SDK_READY, () => {
    Taro.setStorageSync('sdkLoading', false)
    sdkConfig.isReady = true
    console.log('SDK is ready now');
  });
  let imResponse = await wx.$TUIKit.login({ userID: userId, userSig: res.data });
  if (imResponse.data.repeatLogin === true) {
  }

  
  
}

export const destroySdk = () => {
  try {
    wx.$TUIKit?.destroy()
    sdkConfig.isReady = false
    // wx.$TUIKit?.logout()
  } catch (error) {
    
  }
  
}


